package pri.damai.xiaowu.common.core.util;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import pri.damai.xiaowu.common.core.enums.ResultCommonEnum;
import pri.damai.xiaowu.common.core.enums.base.StringEnumerator;
import pri.damai.xiaowu.common.core.exception.GlobalException;

import java.util.Collection;

/**
 * @author DaMai
 * @description: 抛出异常工具类
 * @date 2020/4/20 18:26
 */
@Slf4j
public class ExceptionUtil {

    public static void isBlank(String o, String msg) {
        if (StringUtils.isBlank(o)) {
            throwException(msg);
        }
    }

    public static void isBlankAndLog(String o, String msg, String logTemplate, Object... objects) {
        if (StringUtils.isBlank(o)) {
            log.warn(logTemplate, objects);
            throwException(msg);
        }
    }


    public static void isEmpty(Collection<?> o, String msg) {
        if (CollectionUtil.isEmpty(o)) {
            throwException(msg);
        }
    }

    public static void isEmptyAndLog(Collection<?> o, String msg, String logTemplate, Object... objects) {
        if (CollectionUtil.isEmpty(o)) {
            log.warn(logTemplate, objects);
            throwException(msg);
        }
    }

    public static void isNullAndLog(Object o, String msg, String logTemplate, Object... objects) {
        if (o == null) {
            log.warn(logTemplate, objects);
            throwException(msg);
        }
    }

    public static void isNull(Object o, String msg) {
        if (o == null) {
            throwException(msg);
        }
    }

    public static void ifTureThrow(boolean flag, String msg) {
        if (flag) {
            throwException(msg);
        }
    }

    public static void ifTureThrowAndLog(boolean flag, String msg, String logTemplate, Object... objects) {
        if (flag) {
            log.warn(logTemplate, objects);
            throwException(msg);
        }
    }

    public static void ifTureThrow(boolean flag, StringEnumerator enumerator) {
        if (flag) {
            throwException(enumerator);
        }
    }

    public static void ifTureThrowAndLog(boolean flag, StringEnumerator enumerator, String logTemplate, Object... objects) {
        if (flag) {
            log.warn(logTemplate, objects);
            throwException(enumerator);
        }
    }

    public static void throwException(StringEnumerator resultEnum) {
        throw new GlobalException(resultEnum);
    }

    public static void throwException(String msg) {
        throw new GlobalException(ResultCommonEnum.BUSINESS_CHECK_EXCEPTION.code(), msg);
    }
}
